package com.hd.crdao.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseSecondActivity;
import com.hd.crdao.bean.LocationForAreaBean;
import com.hd.crdao.bean.MessageBean;
import com.hd.crdao.bean.MessageEvent;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Programming
 *@date 2017/5/22 0022
 */
public class ChangeAddressActivity extends BaseSecondActivity {


    private static final int GETDETAILADRESS = 100;
    @BindView(R.id.changeaddress)
    ExpandHeadView mChangeaddress;
    @BindView(R.id.cityareaName)
    TextView mCityareaName;
    @BindView(R.id.cityarea)
    LinearLayout mCityarea;
    @BindView(R.id.detailaddress)
    EditText mDetailaddress;
    public String cbXy;


    @Override
    protected void initView() {
        //回显数据 回显的数据一定要包括省市区三级,比如 福建省福州市鼓楼区+详细地址

        final String allAddress = getIntent().getStringExtra("allAddress");
        if (allAddress.contains(",")) {
            int indexOf = allAddress.indexOf(",");
            String provinceCityArea = allAddress.substring(0, indexOf+1);
            if(provinceCityArea.contains(",")){
                provinceCityArea= provinceCityArea.replace(",","");
            }
            String detailaddress = allAddress.substring(indexOf, allAddress.length());
            if(detailaddress.contains(",")){
                detailaddress= detailaddress.replace(",","");
            }
            if (TextUtils.isEmpty(provinceCityArea)) {
                mCityareaName.setText("请选择");
            } else {
                mCityareaName.setText(provinceCityArea);
            }
            if (!TextUtils.isEmpty(detailaddress)) {
                mDetailaddress.setText(detailaddress);
            } else {
                mDetailaddress.setHint("请输入详细地址");
            }
        }

        EventBus.getDefault().register(this);
        mChangeaddress.getHeadViewRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String cityName = mCityareaName.getText().toString().trim();
                String detailAddress = mDetailaddress.getText().toString().trim();
                SPUtils.saveString(Config.provinceCityArea, cityName);
                SPUtils.saveString(Config.detailAddress, detailAddress);
                ALog.d("保存按钮被点击");
                //CheckLocation(allAddress);
                TransferLocation(cityName, detailAddress);
            }
        });
    }

    /**
     *修改车商地址信息
     */
    private void updateCarBusinessInfo(String allAddress) {
        String busnissid = SPUtils.getString(Config.businessId, "");
        String aredid = SPUtils.getString(Config.areaId, "");
        OkHttpUtils.post().url(Constants.CHANGECARBUSINESS_URL)
                .addParams("sign", Constants.SIGN)
                .addParams("appFlag", "true")
                .addParams("id", busnissid)
                .addParams("areaId", aredid)
                .addParams("cbAddress", allAddress)
                .addParams("cbxy", cbXy)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络开了个小差");
            }

            @Override
            public void onResponse(String response, int id) {
                MessageBean messageBean = new Gson().fromJson(response, MessageBean.class);
                if (messageBean.getSuccess() == 0) {
                    MyToast.show(messageBean.getMessage());
                    finish();
                } else {
                    MyToast.show(messageBean.getMessage());
                }
            }
        });
    }

    /**
     * 使用百度地图WEBAPI查询地址<==>经纬度互转
     *
     * @param address
     */
    private void CheckLocation(final String address) {
       /* address:福建省福州市鼓楼区树汤路51号
        output:json
        ak:ogb7qtmDrZ9KyqqTTOEBPcpNDMeiqMhn
        callback:showLocation*/
        String url = "http://api.map.baidu.com/geocoder/v2/";
        OkHttpUtils.post().url(url)
                .addParams("output", "json")
                .addParams("address", address)
                .addParams("ak", "ogb7qtmDrZ9KyqqTTOEBPcpNDMeiqMhn")
                .addParams("callback", "showLocation")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络不佳,请稍后重试");
            }

            @Override
            public void onResponse(String response, int id) {

                if (response.contains("<?xml version=\"1.0\" encoding=\"utf-8\"?>")) {
                    MyToast.show("请输入正确的详细地址");
                } else {
                    LocationForAreaBean locationForAreaBean = new Gson().fromJson(response, LocationForAreaBean.class);
                    if (locationForAreaBean.getStatus() == 0) {
                        LocationForAreaBean.ResultBean.LocationBean location = locationForAreaBean.getResult().getLocation();

                        finish();
                    } else {
                        MyToast.show("请输入正确的地址");
                    }
                }
            }
        });

    }

    /**
     * 百度地图经纬度和地址转换
     *
     * @param cityName
     * @param detailAddress
     */
    public void TransferLocation(final String cityName, final String detailAddress) {
        if (TextUtils.isEmpty(cityName) || TextUtils.isEmpty(detailAddress)) {
            MyToast.show("地址信息不能为空哦");
            return;
        }
        GeoCoder gc = GeoCoder.newInstance();
        GeoCodeOption geoCodeOption = new GeoCodeOption();
        geoCodeOption.city(cityName);
        geoCodeOption.address(detailAddress);
        gc.geocode(geoCodeOption);
        gc.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    MyToast.show("您输入的地址不存在,请检查后输入!");
                } else {
                    LatLng location = geoCodeResult.getLocation();
                    cbXy = location.latitude + "," + location.longitude;
                    String dowhat = getIntent().getStringExtra("dowhat");
                    MessageEvent messageEvent = new MessageEvent();
                    messageEvent.setAddress(cityName + detailAddress);
                    messageEvent.setLocation(cbXy);
                    EventBus.getDefault().post(messageEvent);
                    SPUtils.saveString("location", cbXy);
                    if (TextUtils.equals(dowhat, "update")) {
                        updateCarBusinessInfo(detailAddress);
                    } else {
                        finish();
                    }
                }
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
            }
        });
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_changeaddress;
    }

    @Override
    protected ExpandHeadView setExpandHeadView() {
        return mChangeaddress;
    }


    @OnClick({R.id.cityarea})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cityarea:
                startActivityForResult(new Intent(UIUtils.getContext(), SelectProvinceActivity.class), GETDETAILADRESS);
                break;


        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEvent(MessageEvent messageEvent) {
        mCityareaName.setText(messageEvent.getAddress());
        ALog.d(messageEvent.getAddress());
        SPUtils.saveString("cityName", messageEvent.getAddress());
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }


}
